package com.wt.chat.config.interceptor;

import com.wt.chat.cache.RedisCache;
import com.wt.chat.context.ContextHolder;
import com.wt.chat.context.SpringContext;
import com.wt.chat.mapper.KefuMapper;
import com.wt.chat.mapper.UserMapper;
import com.wt.chat.utils.CookieUtils;
import com.wt.chat.utils.Keys;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @description
 * @author: wangtao
 * @date:18:12 2019/11/8
 * @email:taow02@jumei.com
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        String requestUrl = request.getRequestURI().replace(request.getContextPath(), "");
        logger.info("拦截到请求: {}", requestUrl);
        if(requestUrl.equals("/") || requestUrl.contains("login") || requestUrl.endsWith(".js") || requestUrl.endsWith(".css") || requestUrl.endsWith("png") || requestUrl.endsWith("jpg")){
            return super.preHandle(request, response, handler);
        }
        String token = CookieUtils.getCookie(request, Keys.LOGIN_COOKIE_KEY);
        if (StringUtils.isEmpty(token) || checkAndInit(token)) {
            response.sendRedirect("/");
            return false;
        }
        return super.preHandle(request, response, handler);
    }

    private boolean checkAndInit(String token) {
		Integer userId = SpringContext.getBean(RedisCache.class).get(token, Integer.class);
		ContextHolder.registerCurrentUserId(1);
        return SpringContext.getBean(UserMapper.class).selectByPrimaryKey(userId) == null;
    }
}
